/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.farent.solutions.plugins.stripes.hyperstripes.core;

import java.io.InputStream;
import javax.xml.namespace.QName;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

/**
 *
 * @author farouka
 */
public class HSPageParser {

    public static void processTemplateWithReader(InputStream fis,
            ComponentModel current, StripesApplicationContext applicationContext)
            throws XMLStreamException {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        XMLStreamReader streamReader = factory.createXMLStreamReader(fis);
        try {
            int event = streamReader.getEventType();
            while (true) {
                switch (event) {
                    case XMLStreamConstants.START_DOCUMENT:
                        break;
                    case XMLStreamConstants.ENTITY_DECLARATION:
                        break;
                    case XMLStreamConstants.START_ELEMENT:
                        QName qName = streamReader.getName();
                        String name = qName.getLocalPart();
                        if( name.equalsIgnoreCase("pageWrapper") )
                        {
                            current.processTag(streamReader);
                        }
                        else
                        {
                            ComponentModel model = ComponentTagModelFactory.getInstance().
                                    getTagModelForTag(qName, applicationContext);

                            if (model != null) {
                                model.processTag(streamReader);
                                model.setParent(current);
                                if (current != null) {
                                    current.AddChild(model);
                                }
                                current = model;
                            }
                        }
                        break;
                    case XMLStreamConstants.CHARACTERS:
                        if (streamReader.isWhiteSpace()) {
                            break;
                        }
                        current.setText(streamReader.getText());
                        break;
                    case XMLStreamConstants.END_ELEMENT:
                        if ( current != null ) {
                            current = current.getParent();
                        }
                        break;
                    case XMLStreamConstants.END_DOCUMENT:
                        break;
                }

                if (!streamReader.hasNext()) {
                    break;
                }
                event = streamReader.next();
            }
        }
        finally  {
            streamReader.close();
        }
    }
}
